"""
@project: colour_life
@author: kang 
@github: https://github.com/fsksf 
@since: 2021/5/19 5:35 PM
"""


import inspect


from vcat.server.routes import as_page, MAIN_ROUTES_BROKER, Children
from vcat.server import (REST_HANDLERS, TABLE_METAS, BROKER_METAS)


class OpenApiDecorate:
    """API 装饰器
        name:
    """

    def __init__(self, name=None):
        self.name = name

    def __call__(self, original_func):
        def _api_func(s1, *arg, **kwargs):
            return original_func(s1, *arg, **kwargs)

        _doc = inspect.getdoc(original_func)
        _description = _doc.split("\n")[0] if _doc else ""
        _api_func.__api_description = _description

        return _api_func


def add_handler(handler):
    REST_HANDLERS.append(handler)
    return handler


def as_table(page_name):
    def warp(model):
        name = model.__name__
        if name in TABLE_METAS:
            raise ValueError(f'table name {name} 已经存在')
        TABLE_METAS[page_name][name] = model.meta()
        return model

    return warp


def as_gateway(gateway_ins: "BaseGateway"):

    broker_name = gateway_ins.gateway_name
    BROKER_METAS[broker_name] = gateway_ins.config_setting.meta()
    title = BROKER_METAS[broker_name]['title']
    as_page(MAIN_ROUTES_BROKER)(
        Children(name=broker_name, path=broker_name, component='broker',
                 props={'pageName': broker_name, 'title': title},
                 meta={'icon': '', 'title': title}
                 )
    )
    return gateway_ins


if __name__ == '__main__':
    from vcat.interface import BaseGateway
